package com.acme.bankapp.domain.bank;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.acme.bankapp.domain.client.Client;
import com.acme.bankapp.domain.client.ClientExistsException;
import com.acme.bankapp.service.ClientRegistrationListener;

@SuppressWarnings("serial")
public class Bank implements Serializable {

	private static final String ERR_CLIENT_EXISTS = "client '%s' already exists";

	private List<Client> clients = new ArrayList<>();
	private List<ClientRegistrationListener> listeners = new ArrayList<>();

	public void addClientRegistrationListener(ClientRegistrationListener listener) {
		listeners.add(listener);
	}

	public void addClient(Client client) throws ClientExistsException {
		String clientSalutation = client.getClientSalutation();
		for (Client existingClient : clients) {
			if ( clientSalutation.equals(existingClient.getClientSalutation()) ) {
				throw new ClientExistsException(String.format(ERR_CLIENT_EXISTS, clientSalutation));
			}
		}
		
		clients.add(client);

		for (ClientRegistrationListener listener : listeners) {
			listener.onClientAdded(client);
		}
	}
	
	public List<Client> getClients() {
		return Collections.unmodifiableList(clients);
	}

}
